package com.hbase.dao.resolve;

import java.lang.reflect.Field;
import java.util.List;

import org.apache.hadoop.hbase.util.Bytes;

import com.google.common.collect.Lists;
import com.hbase.dao.annotation.HBaseTable;
import com.hbase.dao.exception.HBaseDaoException;
import com.hbase.dao.util.CheckUtil;
import com.hbase.dao.util.FieldUtil;

/**
 * HBaseTableEntityAnnotation
 * 
 * @author yangshenhui
 * @version 1.0
 */
public class HBaseTableEntityAnnotation {
	private Class<?> clazz;
	private Field hBaseRowkeyField;
	private List<Field> hBaseColumnFieldList;

	public void addHBaseColumn(Field field) {
		if (CheckUtil.isNull(hBaseColumnFieldList)) {
			hBaseColumnFieldList = Lists.newArrayList();
		}
		hBaseColumnFieldList.add(field);
	}

	public <T> byte[] getRowKey(T t) throws HBaseDaoException {
		CheckUtil.checkNull(t);
		Object rowKeyValue = null;
		if (CheckUtil.isNotNull(hBaseRowkeyField)) {
			if (t.getClass() == clazz) {
				rowKeyValue = FieldUtil.getFieldValue(t, hBaseRowkeyField);
			}
		}
		byte[] rowKeyBytes = null;
		if (CheckUtil.isNotNull(rowKeyValue)) {
			rowKeyBytes = Bytes.toBytes(rowKeyValue.toString());
		}
		return rowKeyBytes;
	}

	public <T> void setRowKey(T t, byte[] rowKeyBytes) throws HBaseDaoException {
		CheckUtil.checkNull(t);
		CheckUtil.checkNull(rowKeyBytes);
		if (t.getClass() == clazz) {
			FieldUtil.setFieldValue(t, hBaseRowkeyField, rowKeyBytes);
		}
	}

	public HBaseTable getHBaseTable() {
		CheckUtil.checkNull(clazz);
		return clazz.getAnnotation(HBaseTable.class);
	}

	public Class<?> getClazz() {
		return clazz;
	}

	public void setClazz(Class<?> clazz) {
		this.clazz = clazz;
	}

	public Field gethBaseRowkeyField() {
		return hBaseRowkeyField;
	}

	public void sethBaseRowkeyField(Field hBaseRowkeyField) {
		this.hBaseRowkeyField = hBaseRowkeyField;
	}

	public List<Field> gethBaseColumnFieldList() {
		return hBaseColumnFieldList;
	}

	public void sethBaseColumnFieldList(List<Field> hBaseColumnFieldList) {
		this.hBaseColumnFieldList = hBaseColumnFieldList;
	}

}